import React, { Component } from 'react';
import { StyleSheet, View,Clipboard,Linking,AppState } from 'react-native';
import { Button, WhiteSpace, List, TextareaItem, Toast } from "antd-mobile";
import {getUserData} from './api';
export default class App extends Component {
  constructor(props){
    super(props);
    this.state={
      textFromClipboard:'燕宝SK在火山分享了视频，快来围观！传送门戳我>>http://reflow.huoshan.com/share/item/6606599358110502147/?tag=10078&timestamp=1538579171&&share_ht_uid=59965813472&did=40164582828&utm_medium=huoshan_android&tt_from=copy_link&iid=45095394702&app=live_stream',
      newUrl:'',
      currentAppState: AppState.currentState,
    };
  }
  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }
  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }
  //
  _handleAppStateChange = (nextAppState) =>{
    this.pasteFromClipboard()
  }
  //从剪贴板中读取字符串
  pasteFromClipboard() {
    Clipboard.getString().then(
      (textFromClipboard) => {
        this.setState({textFromClipboard});
      }
    ).catch(
      (error) => {
        Toast.fail("从剪贴板中读取数据错误!");
      }
    );
  }
  //向剪贴板中存入字符串
  copyToClipBoard(url) {
    Clipboard.setString(url);
  }
  //获取输入框的内容
  getValue(e){
    this.setState({
      textFromClipboard:e
    })
  }
  //跳转到qq浏览器下载
  goUpdate(con){
    if(!con&&con.indexOf("https")==-1&&con.indexOf("http")==-1){
      Toast.fail("地址错误!")
      return;
    } 
    let httpOrHttps ='';
    if(con.indexOf("https")>0){
      httpOrHttps=`https${con.split('https')[1]}`
    }else if(con.indexOf("http")>0){
      httpOrHttps=`http${con.split('http')[1]}`
    }
    getUserData(httpOrHttps);
    this.setState({
      textFromClipboard:httpOrHttps,
      newUrl:httpOrHttps
    })
    this.openExplorer(httpOrHttps);
  }
  //打开浏览器
  openExplorer(url){
    if(!url) {
      Toast.fail("地址错误!");
      return;
    }
    Linking.openURL(url)  
     .catch((err)=>{  
        Toast.fail("浏览器打开错误");
     });
  }
  render() {
    const { textFromClipboard } =this.state;
    return (
      <View>
        <WhiteSpace/>
        <List renderHeader={() => '检测到您的网址'}>
          <TextareaItem
            value={textFromClipboard}
            style={[styles.content]}
            title="高度自适应" 
            autoHeight
            labelNumber={5}
            rows={5}
            onChange={(e)=>this.getValue(e)}
          />
        </List>
        <WhiteSpace/>
        <Button type="primary" onClick={()=>this.goUpdate(textFromClipboard)}>点击跳转</Button>
      </View>
    );
  }
} 
const styles = StyleSheet.create({
  content: {
    height:300,
    fontSize: 20,
    borderWidth:1,
    borderColor:"red",
  },
});
